# Copyright (C) 2007 "dbsolution sas" 
#
# This file is part of Weebotee.
#
# Weebotee is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Weebotee is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Weebotee.  If not, see <http://www.gnu.org/licenses/>.

from django.template import Library, loader, Context
from django.http import HttpResponseRedirect
from apps.core.backend.views.forms.user_form import BaseRegistrationForm, LoginForm
from django.contrib.auth.models import User
from apps.core.backend.views.forms.user_form import userFormFe
from apps.core.models.Udetail import Udetail
from django.core.mail import send_mail
import string
from random import choice

register = Library()

def get_registration_form(context):
    if context["post"]:
        form =  BaseRegistrationForm(context["post"])
        if form.is_valid():
            form.save()
            return {"registered":True}
    else:
        form = BaseRegistrationForm()
    return {"form":form}
register.inclusion_tag('widgets/registration_form.html', takes_context=True)(get_registration_form)

###
# LOGIN FORM WIDGET TEMPLATETAG
#
def get_login_form(context):
    user = context["request"].user
    tested = False
    if context["post"]:
        form = LoginForm(context["post"])
        if form.is_valid():
            user = form.save(context['request'])
            tested = True 
    else:
        form = LoginForm()
    return {"form":form, "user":user, 'tested':tested}
register.inclusion_tag('widgets/login_form.html', takes_context=True)(get_login_form)

def get_forgot_password_form(context):
    if context["request"].method == 'POST':
        try:
            u = User.objects.get(email=context["post"].get("email"))
            chars = string.letters + string.digits
            newpasswd = ""
            for i in range(10):
                newpasswd += choice(chars)
            u.set_password(newpasswd)
            u.save()
            new_password_request = loader.get_template('mail_new_password.txt')
            mail_context = {
                'userName':u.username,
                'nome':u.first_name,
                'cognome':u.last_name,
                'password':newpasswd
            }
            send_mail('[ClickToSpeak] Richiesta recupero password',
                        new_password_request.render(Context(mail_context)),
                        'staff@webotee.it',
                        [u.email,],
                        fail_silently=False)
        except Exception, e:
            print e
        
        end = True
    else:
        end = False
    
    return {"end":end}
register.inclusion_tag('widgets/forgotpassword_form.html', takes_context=True)(get_forgot_password_form)

def get_profile_form(context):
    u = context["request"].user
    ud = Udetail.objects.get(user = u.id)
    initial = { 
        "email":u.email, 
        "first_name":u.first_name, 
        "last_name":u.last_name, 
        "web_site":ud.website, 
        "address":ud.address, 
        "city":ud.city, "prov":ud.prov,
        "cap":ud.cap, "company":ud.company, 
        "tel":ud.tel, "fax":ud.fax,"piva":ud.piva
    }
    if context["post"]:
        form = userFormFe(oldusername=u.username,data=context["post"],initial=initial)
        if form.is_valid():
            form.save()
    else:
        form = userFormFe(oldusername=u.username,data=initial)
    return {"form":form}
register.inclusion_tag('widgets/profile_form.html', takes_context=True)(get_profile_form)
